<template>
  <div class="add-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        :closable="false"
        show-icon>
      </el-alert>

      <el-steps 
        :active="activeIndex - 0"
        align-center
        finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form 
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm" 
        label-position="top"
        label-width="100px" 
        class="demo-ruleForm">
        <el-tabs 
          v-model="activeIndex" 
          tab-position="left" 
          @tab-click="tabClick"
          :before-leave="beforeLeave"
          style="min-height: 350px;">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="ruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="ruleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="ruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item 
              v-for="item in manyTabList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox border v-for="(item2, index2) in item.attr_vals" :key="index2" :label="item2"></el-checkbox>
            </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTabList"
              :key="item.attr_id"
              :label="item.attr_name" >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadImgURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="uploadHeader"
              list-type="picture">
              <el-button size="small" type="primary">上传图片</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              ref="myQuillEditor"
              v-model="ruleForm.goods_introduce"
              :options="editorOption"
            />
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog
      title="图片预览"
      :visible.sync="previewDialog"
      width="50%"
      >
      <img :src="previewImg" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data(){
    return {
      editorOption: {},
      activeIndex: '0',
      uploadImgURL: 'http://wanghongde.top:8888/api/private/v1/upload',
      uploadHeader: {
        Authorization: window.sessionStorage.getItem('token')
      },
      ruleForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      },
      cateList: [],
      cateProps: { 
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name' 
      },
      manyTabList: [],
      onlyTabList: [],
      previewImg: '',
      previewDialog: false
    }
  },
  created(){
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const {data: res} = await this.$http.get(`categories`)

      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.cateList = res.data
    },
    handleChange() {
      if(this.ruleForm.goods_cat.length !== 3) {
        this.ruleForm.goods_cat.length = []
      }
    },
    beforeLeave(activeName, oldActiveName) {
      if(oldActiveName === '0' && this.ruleForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    async tabClick() {
      if(this.activeIndex === '1') {
        const {data: res} = await this.$http.get(`categories/${this.ruleForm.goods_cat[2]}/attributes`, {
          params: {sel: 'many'}
        })

        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
        })

        this.manyTabList = res.data
      } else if(this.activeIndex === '2') {
        const {data: res} = await this.$http.get(`categories/${this.ruleForm.goods_cat[2]}/attributes`, {
          params: {sel: 'only'}
        })

        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        this.onlyTabList = res.data
        console.log(this.onlyTabList)
      }
    },
    handleRemove(file, fileList) {
      const path = file.response.data.tmp_path

      const i = this.ruleForm.pics.findIndex(item => {
        return item.pic === path
      })

      this.ruleForm.pics.splice(i, 1)
    },
    handlePreview(file) {
      this.previewImg = file.response.data.url.replace('http://127.0.0.1', 'http://wanghongde.top')

      this.previewDialog = true


    },
    handleSuccess(res) {
      this.ruleForm.pics.push({
        pic: res.data.tmp_path
      })

      console.log( this.ruleForm )
    },
    addGoods() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          this.$message.error('请填写完整表单')
          return false
        } 

        let form = JSON.parse(JSON.stringify( this.ruleForm ))

        form.goods_cat = form.goods_cat.join(',')

        this.manyTabList.forEach(item => {
          let obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_name
          }

          form.attrs.push(obj)
        })
     
        this.onlyTabList.forEach(item => {
          console.log( item )
          let obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_name
          }

          form.attrs.push(obj)
        })
     
        const {data: res} = await this.$http.post('goods', form)

        if(res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }

        this.$message.success(res.meta.msg)

        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less">
.add-container{
  .el-card{
    margin: 20px 0;
  }
  .el-steps{
    margin: 10px 0;
  }
  .el-step__title{
    font-size: 13px!important;
  }
  .el-cascader {
    width: 260px;
  }
  .el-dialog  img{
    width: 100%;
  }
  .ql-container{
    height: 350px;
    margin-bottom: 20px;
  }
}
</style>
